import datetime
import json
import os

import pymysql
import requests
import time

from Base import Log, GetYamlFile
from Base.GetYamlFile import getYamlPath
from Base.HttpBase import HttpBase
from Base.ReadExcel import Read_Excel

log = Log.Log()
# base_url = 'http://192.168.17.236:30810'  # 独立租户2环境
base_url = 'http://192.168.17.236:30510'  # 独立租户1环境
tenant_id = 1  # 独立租户1环境
# base_url = 'http://111.20.218.54:30510'  # 凤县线上环境
# tenant_id =2561 # 凤县线上环境
login_api = base_url + '/upms-provider/tenant/user/login/mobile'

is_list = ['甘肃永诺物流有限公司(王娟)', '甘肃永诺物流有限公司', '两当县陇源通商贸有限责任公司(张亮)', '两当县陇源通商贸有限责任公司', '陕西安顺腾达物流有限公司', '凤县鼎泰工贸运输有限公司(杨晓云)',
           '凤县鼎泰工贸运输有限公司', '凤县安信商贸行', '宝鸡鼎诚汇金商贸有限公司', '零售LS', '林洲测试客户07311', '宝鸡海中建筑工程有限公司', '陕西鑫邦永顺建筑劳务有限公司']
login_data = {
    'mobile': '18368093710',
    'password': 'Aa123456'
}
headers = {
    'Content-Type': 'application/json'
}
token = HttpBase(login_api, login_data, 'post', headers).getHttpHeaders().get('access_token')
Refresh_token = HttpBase(login_api, login_data, 'post', headers).getHttpHeaders().get('Refresh_token')
log.info(token)

# 基础请求头
base_headers = {
    'type': 'tenant',
    'tenant_id': tenant_id,
    'access_token': token,
    'Refresh_token': Refresh_token,
    # 'Version': 'middleground-2.0.5.6-SNAPSHOT'
}


def is_result_true(flag, url, data, header_list):
    while flag is False:
        result = requests.post(url, json=data, headers=header_list)
        while result.status_code != 200:
            log.error("服务器返回异常，休眠10s后重新发送请求")
            log.error("失败记录：" + str(result.content, 'utf-8'))
            time.sleep(10)
            result = requests.post(url, json=data, headers=header_list)
        log.info(str(result.content, 'utf-8'))
        log.info('运行时间：%s秒' % str(result.elapsed.seconds))
        result = json.loads(str(result.content, 'utf-8'))
        flag = dict(result)['success']


def price_add():
    """
价格单导入
    """
    page_union_url = base_url + '/tenant-lms-basic-provide/lms/basic/customer/pageUnion'
    project_customer_url = base_url + '/tenant-lms-basic-provide/projectCustomer/list'
    product_url = base_url + '/tenant-lms-basic-provide/lms/basic/product/list'
    price_add_url = base_url + '/tenant-lms-price-provide/priceList/save'
    add_headers = base_headers
    yml_list = GetYamlFile.getYamlFile()
    pricePath = yml_list["pricePath"]
    PROJECT_ROOT = os.path.dirname(os.path.dirname(__file__))
    REPORT_XLSX_DIR = os.path.join(PROJECT_ROOT, pricePath)
    readBook = Read_Excel(REPORT_XLSX_DIR)
    num = readBook.get_RowNums("sheet")
    print(num)
    list1 = []

    for i in range(1, num):
        product_name = readBook.read_Excel("sheet", i, 7)
        product_code = readBook.read_Excel("sheet", i, 6)
        customer_code = readBook.read_Excel("sheet", i, 2)
        jiesuan = readBook.read_Excel("sheet", i, 12)
        jiesuancode = readBook.read_Excel("sheet", i, 11)
        price = readBook.read_Excel("sheet", i, 14)

        customer_data = {
            'status': 0,
            'auditStatus': 1,
            'current': 1,
            'size': 10,
            'nameOrCode': customer_code
        }
        print(customer_code)
        result = requests.get(page_union_url, customer_data, headers=add_headers)
        customer_name = json.loads(result.content).get("data").get('records')[0].get('name')
        customer_id = json.loads(result.content).get("data").get('records')[0].get('id')
        customer_code = json.loads(result.content).get("data").get('records')[0].get('code')
        customer_category_name = json.loads(result.content).get("data").get('records')[0].get('customerCategoryName')
        customer_category_id = json.loads(result.content).get("data").get('records')[0].get('customerCategoryId')
        customer_short_name = json.loads(result.content).get("data").get('records')[0].get('shortName')
        project_customer_data = {
            'customerId': customer_id,
            'status': 1
        }
        project_customer_result = requests.get(project_customer_url, project_customer_data, headers=add_headers)
        print(str(project_customer_result.content, 'utf-8'))
        product_data = {
            'auditStatus': 1,
            'productCode': product_code,
            'current': 1,
            'size': 5
        }
        product_result = requests.get(product_url, product_data, headers=add_headers)
        print(str(product_result.content, 'utf-8'))
        price_list_name = json.loads(project_customer_result.content).get("data")[0].get(
            'projectName') + '-' + product_name + '-' + jiesuan + '价目表'
        price_add_data = {
            "isAdjust": 1,
            "tenantId": 2561,
            "endExpireTime": "",
            "priceListName": price_list_name,
            "customerId": customer_id,
            "customerCode": customer_code,
            "customerName": customer_name,
            "customerCategoryName": customer_category_name,
            "customerCategoryId": customer_category_id,
            "customerSalesType": None,
            "customerSalesTypeName": None,
            "customerShortName": customer_short_name,
            "siteId": "",
            "startExpireTime": "2023-08-18 17:03:34",
            "checkStatus": 1,
            "priceListGoodsQos": [{
                "categoryId": json.loads(product_result.content).get("data").get('records')[0].get('categoryId'),
                "productId": json.loads(product_result.content).get("data").get('records')[0].get('id'),
                "productName": json.loads(product_result.content).get("data").get('records')[0].get('productName'),
                "productCode": json.loads(product_result.content).get("data").get('records')[0].get('productCode'),
                "categoryName": json.loads(product_result.content).get("data").get('records')[0].get('category'),
                "unitName": json.loads(product_result.content).get("data").get('records')[0].get('unit'),
                "unitId": json.loads(product_result.content).get("data").get('records')[0].get('unitId'),
                "price": price,
                "productPrice": price,
                "transportPrice": 0,
                "taxRate": json.loads(product_result.content).get("data").get('records')[0].get('taxRate'),
                "currency": "人民币",
                "priceModel": 2,
                "flowControl": 2,
                "payType": jiesuancode,
                "siteId": "",
                "projectId": json.loads(project_customer_result.content).get("data")[0].get('projectId'),
                "num": 1,
                "key": 0,
                "projectName": json.loads(project_customer_result.content).get("data")[0].get('projectName'),
                "subAccountId": json.loads(project_customer_result.content).get("data")[0].get('subAccountId'),
                "payTypeName": jiesuan
            }],
            "businessRouteUrl": "/lms-web/#/dealPriceDetailH5?id=",
            "priceListType": 2,
            "tenantName": "凤县声威建材有限公司"
        }
        print(product_code, customer_code, i)
        post_header = base_headers
        post_header['Content-Type'] = 'application/json'
        result = requests.post(price_add_url, json=price_add_data, headers=post_header)
        print(str(result.content, 'utf-8'))
        # print('拿到code:'+str(json.loads(result.content).get('code')))
        if json.loads(result.content).get('code') != 0:
            print('----执行失败，记录code-----')
            list1.append(customer_code)
    print(list1)


if __name__ == '__main__':
    price_add()
